"""
接济单管理系统 - 业务逻辑层
提供接济单的创建、查询、更新状态等业务逻辑功能
"""

import json
import mysql.connector
from datetime import datetime
from config import MYSQL_CONFIG
from typing import List, Dict, Optional, Any


class DateEncoder(json.JSONEncoder):
    """处理日期对象的JSON序列化问题"""
    def default(self, obj):
        if isinstance(obj, (datetime)):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        return super().default(obj)


def get_db_connection():
    """获取数据库连接"""
    return mysql.connector.connect(**MYSQL_CONFIG)


def create_relief_form(recipient_id: str, recipient_name: str, issuer_id: str, 
                      issuer_name: str, items: str, remark: str = "", total_value: float = 0.0) -> Optional[int]:
    """
    创建接济单
    
    Args:
        recipient_id: 接收人ID
        recipient_name: 接收人姓名
        issuer_id: 开具人ID
        issuer_name: 开具人姓名
        items: 物品清单（可以是对象数组或字符串）
        remark: 备注
    
    Returns:
        int: 接济单ID，如果创建失败则返回None
    """
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 生成接济单编号
        form_id = generate_form_number()
        
        # 处理物品清单 - 简化为直接存储字符串
        items_json = items  # 直接使用传入的字符串
        
        # 插入接济单记录
        query = """
            INSERT INTO relief_forms 
            (form_id, recipient_id, recipient_name, issuer_id, issuer_name, items, total_value, remark, status)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        """
        
        cursor.execute(query, (
            form_id, recipient_id, recipient_name, issuer_id, issuer_name, 
            items_json, total_value, remark, 'draft'
        ))
        
        conn.commit()
        
        # 返回新创建的接济单ID
        return cursor.lastrowid
        
    except mysql.connector.Error as db_err:
        print(f"创建接济单数据库错误: {str(db_err)}")
        if conn:
            conn.rollback()
        return None
    except Exception as e:
        print(f"创建接济单异常: {str(e)}")
        if conn:
            conn.rollback()
        return None
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()


def get_relief_form(form_id: int) -> Optional[Dict[str, Any]]:
    """
    获取接济单详情
    
    Args:
        form_id: 接济单ID
    
    Returns:
        dict: 接济单详情，如果未找到则返回None
    """
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = "SELECT * FROM relief_forms WHERE id = %s"
        cursor.execute(query, (form_id,))
        result = cursor.fetchone()
        
        if result:
            # items现在是简单字符串，直接返回
            return result
        
        return None
        
    except mysql.connector.Error as db_err:
        print(f"获取接济单详情数据库错误: {str(db_err)}")
        return None
    except Exception as e:
        print(f"获取接济单详情异常: {str(e)}")
        return None
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()


def get_relief_forms_by_status(status: str) -> List[Dict[str, Any]]:
    """
    根据状态获取接济单列表
    
    Args:
        status: 接济单状态
    
    Returns:
        list: 接济单列表
    """
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = "SELECT * FROM relief_forms WHERE status = %s ORDER BY created_at DESC"
        cursor.execute(query, (status,))
        results = cursor.fetchall()
        
        # items现在是简单字符串，直接返回
        
        return results
        
    except mysql.connector.Error as db_err:
        print(f"获取接济单列表数据库错误: {str(db_err)}")
        return []
    except Exception as e:
        print(f"获取接济单列表异常: {str(e)}")
        return []
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()


def update_relief_form_status(form_id: int, status: str, user_id: str, user_name: str) -> bool:
    """
    更新接济单状态
    
    Args:
        form_id: 接济单ID
        status: 新状态
        user_id: 操作用户ID
        user_name: 操作用户姓名
    
    Returns:
        bool: 操作是否成功
    """
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 根据状态更新相应的字段
        time_field = None
        user_field = None
        
        if status == 'pending':
            time_field = 'approved_at'
            user_field = 'approved_by'
        elif status == 'printed':
            time_field = 'printed_at'
            user_field = 'printed_by'
        elif status == 'sent':
            time_field = 'sent_at'
            user_field = 'sent_by'
        elif status == 'received':
            time_field = 'received_at'
            user_field = 'received_by'
        elif status == 'archived':
            time_field = 'archived_at'
            user_field = 'archived_by'
        
        # 构建更新语句
        if time_field and user_field:
            query = f"""
                UPDATE relief_forms 
                SET status = %s, {time_field} = %s, {user_field} = %s
                WHERE id = %s
            """
            cursor.execute(query, (status, datetime.now(), user_name, form_id))
        else:
            query = "UPDATE relief_forms SET status = %s WHERE id = %s"
            cursor.execute(query, (status, form_id))
        
        conn.commit()
        return cursor.rowcount > 0
        
    except mysql.connector.Error as db_err:
        print(f"更新接济单状态数据库错误: {str(db_err)}")
        if conn:
            conn.rollback()
        return False
    except Exception as e:
        print(f"更新接济单状态异常: {str(e)}")
        if conn:
            conn.rollback()
        return False
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()


def get_all_relief_forms() -> List[Dict[str, Any]]:
    """
    获取所有接济单
    
    Returns:
        list: 所有接济单列表
    """
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = "SELECT * FROM relief_forms ORDER BY created_at DESC"
        cursor.execute(query)
        results = cursor.fetchall()
        
        # items现在是简单字符串，直接返回
        
        return results
        
    except mysql.connector.Error as db_err:
        print(f"获取所有接济单数据库错误: {str(db_err)}")
        return []
    except Exception as e:
        print(f"获取所有接济单异常: {str(e)}")
        return []
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()


def get_relief_forms_by_role(user_id: int, user_role: int) -> List[Dict[str, Any]]:
    """
    根据用户角色获取相应的接济单列表
    
    Args:
        user_id: 用户ID
        user_role: 用户角色ID (1-领导, 2-管教, 3-巡控, 4-窗口, 5-指中)
    
    Returns:
        list: 接济单列表
    """
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # 根据不同角色查询不同的接济单
        if user_role == 2:  # 管教
            # 管教可以看到自己开具的所有接济单
            query = "SELECT * FROM relief_forms WHERE issuer_id = %s ORDER BY created_at DESC"
            cursor.execute(query, (user_id,))
        else:
            # 其他角色可以看到所有接济单
            query = "SELECT * FROM relief_forms ORDER BY created_at DESC"
            cursor.execute(query)
        
        results = cursor.fetchall()
        
        # items现在是简单字符串，直接返回
        
        return results
        
    except mysql.connector.Error as db_err:
        print(f"根据角色获取接济单列表数据库错误: {str(db_err)}")
        return []
    except Exception as e:
        print(f"根据角色获取接济单列表异常: {str(e)}")
        return []
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()


def generate_form_number() -> str:
    """
    生成接济单编号
    
    Returns:
        str: 接济单编号
    """
    # 生成格式：JJD-YYYYMMDD-XXXX (JJD表示接济单，YYYYMMDD表示日期，XXXX表示序号)
    today = datetime.now().strftime('%Y%m%d')
    conn = None
    cursor = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 查询今天已有的接济单数量
        query = "SELECT COUNT(*) as count FROM relief_forms WHERE DATE(created_at) = CURDATE()"
        cursor.execute(query)
        result = cursor.fetchone()
        count = result[0] if result else 0
        
        # 生成编号 (序号从0001开始)
        form_number = f"JJD{today}{count+1:04d}"
        return form_number
        
    except mysql.connector.Error as db_err:
        print(f"生成接济单编号数据库错误: {str(db_err)}")
        # 出错时返回默认编号
        return f"JJD-{today}-0001"
    except Exception as e:
        print(f"生成接济单编号异常: {str(e)}")
        # 出错时返回默认编号
        return f"JJD-{today}-0001"
    finally:
        if cursor: 
            cursor.close()
        if conn and conn.is_connected(): 
            conn.close()